<template>
  <div class="vehicle-detail">
    <div class="page-header">
      <el-page-header @back="goBack" :content="`车辆详情 - ${vehicleInfo.plate_number || '加载中...'}`"></el-page-header>
    </div>

    <el-card v-loading="loading" class="detail-card">
      <template #header>
        <div class="card-header">
          <h3>基本信息</h3>
          <el-button type="primary" @click="openEditDialog">编辑</el-button>
        </div>
      </template>

      <el-descriptions :column="3" border>
        <el-descriptions-item label="车牌号">{{ vehicleInfo.plate_number }}</el-descriptions-item>
        <el-descriptions-item label="品牌">{{ vehicleInfo.brand }}</el-descriptions-item>
        <el-descriptions-item label="型号">{{ vehicleInfo.model }}</el-descriptions-item>
        <el-descriptions-item label="颜色">{{ vehicleInfo.color }}</el-descriptions-item>
        <el-descriptions-item label="车辆类型">{{ vehicleInfo.vehicle_type }}</el-descriptions-item>
        <el-descriptions-item label="注册日期">{{ vehicleInfo.register_date }}</el-descriptions-item>
        <el-descriptions-item label="所属人" v-if="vehicleInfo.user">
          {{ vehicleInfo.user.name }}（员工） 
          <div class="owner-details">
            <p>手机：{{ vehicleInfo.user.phone }}</p>
            <p v-if="vehicleInfo.user.company_employee_profile">
              部门：{{ vehicleInfo.user.company_employee_profile.department }}
            </p>
            <p v-if="vehicleInfo.user.company_employee_profile">
              职位：{{ vehicleInfo.user.company_employee_profile.position }}
            </p>
            <p v-if="vehicleInfo.user.company_employee_profile">
              公司：{{ vehicleInfo.user.company_employee_profile.company.name }}
            </p>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="所属人" v-else-if="vehicleInfo.visitor">
          {{ vehicleInfo.visitor.name }}
          <el-tag size="small" type="warning" class="ml-10">访客</el-tag>
          <div class="owner-info">
            <span>手机：{{ vehicleInfo.visitor.phone }}</span>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="所属人" v-else>-</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 可以在这里添加更多卡片，如停车记录、包月记录等 -->

    <!-- 编辑对话框 -->
    <el-dialog title="编辑车辆信息" v-model="dialogVisible" width="600px">
      <el-form
        ref="vehicleFormRef"
        :model="editForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="车牌号" prop="plate_number">
          <el-input v-model="editForm.plate_number" placeholder="请输入车牌号" />
        </el-form-item>
        <el-form-item label="品牌" prop="brand">
          <el-input v-model="editForm.brand" placeholder="请输入品牌" />
        </el-form-item>
        <el-form-item label="型号" prop="model">
          <el-input v-model="editForm.model" placeholder="请输入型号" />
        </el-form-item>
        <el-form-item label="颜色" prop="color">
          <el-input v-model="editForm.color" placeholder="请输入颜色" />
        </el-form-item>
        <el-form-item label="车辆类型" prop="vehicle_type">
          <el-select v-model="editForm.vehicle_type" placeholder="请选择车辆类型" style="width: 100%">
            <el-option label="小轿车" value="小轿车"></el-option>
            <el-option label="SUV" value="SUV"></el-option>
            <el-option label="货车" value="货车"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属类型" prop="owner_type">
          <el-select v-model="editForm.owner_type" placeholder="请选择所属类型" style="width: 100%" @change="handleOwnerTypeChange">
            <el-option label="企业员工" value="employee"></el-option>
            <el-option label="访客" value="visitor"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属人" prop="owner_id">
          <el-select 
            v-model="editForm.owner_id" 
            placeholder="请选择所属人" 
            style="width: 100%" 
            filterable 
            remote 
            :remote-method="handleOwnerSearch"
            :loading="ownerLoading"
          >
            <el-option 
              v-for="item in ownerOptions" 
              :key="item.id" 
              :label="item.name" 
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="注册日期" prop="register_date">
          <el-date-picker 
            v-model="editForm.register_date" 
            type="date" 
            placeholder="选择注册日期"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getVehicleDetail, updateVehicle } from '@/api/assets'

export default {
  name: 'VehicleDetail',
  setup() {
    const router = useRouter()
    const route = useRoute()
    const vehicleId = ref(route.params.id)
    const loading = ref(false)
    
    // 车辆详情数据
    const vehicleInfo = reactive({
      vehicle_id: null,
      plate_number: '',
      brand: '',
      model: '',
      color: '',
      vehicle_type: '',
      register_date: '',
      user: null,
      visitor: null
    })
    
    // 编辑对话框
    const dialogVisible = ref(false)
    const vehicleFormRef = ref(null)
    const editForm = reactive({
      vehicle_id: null,
      plate_number: '',
      brand: '',
      model: '',
      color: '',
      vehicle_type: '',
      owner_type: '',
      owner_id: null,
      register_date: null
    })
    
    // 所属人选择相关
    const ownerOptions = ref([])
    const ownerLoading = ref(false)
    
    // 表单校验规则
    const rules = reactive({
      plate_number: [
        { required: true, message: '请输入车牌号', trigger: 'blur' },
        { pattern: /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-Z0-9]{5,6}$/, message: '请输入正确的车牌号', trigger: 'blur' }
      ],
      vehicle_type: [
        { required: true, message: '请选择车辆类型', trigger: 'change' }
      ],
      owner_type: [
        { required: true, message: '请选择所属类型', trigger: 'change' }
      ],
      owner_id: [
        { required: true, message: '请选择所属人', trigger: 'change' }
      ],
      register_date: [
        { required: true, message: '请选择注册日期', trigger: 'change' }
      ]
    })
    
    // 获取车辆详情
    const fetchVehicleDetail = async () => {
      loading.value = true
      try {
        const response = await getVehicleDetail(vehicleId.value)
        if (response.data && response.data.code === 200) {
          const data = response.data.data
          Object.assign(vehicleInfo, data)
        } else {
          ElMessage.error('获取车辆详情失败')
        }
      } catch (error) {
        console.error('获取车辆详情失败:', error)
        ElMessage.error('获取车辆详情失败')
      } finally {
        loading.value = false
      }
    }
    
    // 返回上一页
    const goBack = () => {
      router.push('/admin/assets/VehicleList')
    }
    
    // 打开编辑对话框
    const openEditDialog = () => {
      resetForm()
      nextTick(() => {
        editForm.vehicle_id = vehicleInfo.vehicle_id
        editForm.plate_number = vehicleInfo.plate_number
        editForm.brand = vehicleInfo.brand
        editForm.model = vehicleInfo.model
        editForm.color = vehicleInfo.color
        editForm.vehicle_type = vehicleInfo.vehicle_type
        
        if (vehicleInfo.user) {
          editForm.owner_type = 'employee'
          editForm.owner_id = vehicleInfo.user.user_id
          ownerOptions.value = [{ id: vehicleInfo.user.user_id, name: vehicleInfo.user.name }]
        } else if (vehicleInfo.visitor) {
          editForm.owner_type = 'visitor'
          editForm.owner_id = vehicleInfo.visitor.visitor_id
          ownerOptions.value = [{ id: vehicleInfo.visitor.visitor_id, name: vehicleInfo.visitor.name }]
        }
        
        editForm.register_date = new Date(vehicleInfo.register_date)
        dialogVisible.value = true
      })
    }
    
    // 重置表单
    const resetForm = () => {
      editForm.vehicle_id = null
      editForm.plate_number = ''
      editForm.brand = ''
      editForm.model = ''
      editForm.color = ''
      editForm.vehicle_type = ''
      editForm.owner_type = ''
      editForm.owner_id = null
      editForm.register_date = null
      ownerOptions.value = []
      
      // 重置表单校验结果
      if (vehicleFormRef.value) {
        vehicleFormRef.value.resetFields()
      }
    }
    
    // 处理所属类型变化
    const handleOwnerTypeChange = () => {
      editForm.owner_id = null
      ownerOptions.value = []
    }
    
    // 搜索所属人
    const handleOwnerSearch = async (query) => {
      if (query === '') {
        ownerOptions.value = []
        return
      }

      ownerLoading.value = true
      try {
        // 根据不同的所属类型，调用不同的API
        // 这里只是示例，实际需要根据后端API接口来实现
        // TODO: 实现根据query搜索用户或访客的API调用
        setTimeout(() => {
          if (editForm.owner_type === 'employee') {
            ownerOptions.value = [
              { id: 1, name: '张三（企业员工）' },
              { id: 2, name: '李四（企业员工）' }
            ]
          } else if (editForm.owner_type === 'visitor') {
            ownerOptions.value = [
              { id: 1, name: '王五（访客）' },
              { id: 2, name: '赵六（访客）' }
            ]
          }
          ownerLoading.value = false
        }, 500)
      } catch (error) {
        console.error('搜索所属人失败:', error)
        ownerLoading.value = false
      }
    }
    
    // 提交表单
    const handleSubmit = () => {
      vehicleFormRef.value.validate(async (valid) => {
        if (!valid) return

        // 日期格式处理函数
        const formatDate = (date) => {
          if (!date) return null;
          if (typeof date === 'string') {
            // 如果是字符串，尝试提取YYYY-MM-DD部分
            return date.split('T')[0];
          } else if (date instanceof Date) {
            // 如果是Date对象，格式化为YYYY-MM-DD
            return date.toISOString().split('T')[0];
          }
          return null;
        };

        const data = {
          plate_number: editForm.plate_number,
          brand: editForm.brand,
          model: editForm.model,
          color: editForm.color,
          vehicle_type: editForm.vehicle_type,
          register_date: formatDate(editForm.register_date) // 格式化日期
        }

        // 根据所属类型，设置不同的ID字段
        if (editForm.owner_type === 'employee') {
          data.user_id = editForm.owner_id
          data.visitor_id = null
        } else if (editForm.owner_type === 'visitor') {
          data.visitor_id = editForm.owner_id
          data.user_id = null
        }

        console.log('提交的数据:', data)
        console.log('更新车辆ID:', vehicleId.value)

        try {
          const response = await updateVehicle(vehicleId.value, data)
          console.log('更新响应:', response)
          ElMessage.success('更新成功')
          dialogVisible.value = false
          fetchVehicleDetail()
        } catch (error) {
          console.error('更新失败:', error)
          console.error('错误详情:', error.response?.data || error.message)
          ElMessage.error(`更新失败: ${error.response?.data?.message || error.message}`)
        }
      })
    }
    
    onMounted(() => {
      fetchVehicleDetail()
    })
    
    return {
      vehicleInfo,
      loading,
      dialogVisible,
      editForm,
      vehicleFormRef,
      rules,
      ownerOptions,
      ownerLoading,
      goBack,
      openEditDialog,
      handleOwnerTypeChange,
      handleOwnerSearch,
      handleSubmit
    }
  }
}
</script>

<style scoped>
.vehicle-detail {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.detail-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.ml-10 {
  margin-left: 10px;
}

.owner-info {
  margin-top: 8px;
  display: flex;
  gap: 16px;
  color: #606266;
  font-size: 14px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style> 